﻿namespace Autodesk.Revit.DB;

/// <summary>
/// Autodesk.Revit.DB.CurveArray的扩展方法
/// </summary>
public static class CurveArrayExtensions
{
    /// <summary>
    /// 获取Curve集合迭代器
    /// </summary>
    /// <param name="curveArray"></param>
    /// <returns></returns>
    public static IEnumerable<Curve> GetEnumerable(this CurveArray curveArray)
    {
        for (int i = 0; i < curveArray.Size; i++)
        {
            yield return curveArray.get_Item(i);
        }
    }

    /// <summary>
    /// 转换成模型线
    /// </summary>
    /// <param name="curveArray"></param>
    /// <param name="doc"></param>
    /// <param name="isFamilyCreate"></param>
    /// <param name="plane"></param>
    /// <returns></returns>
    public static ModelCurveArray ConvertToModelCurveArray(this CurveArray curveArray, Document doc, bool isFamilyCreate = false, Plane? plane = null)
    {
        if (plane is null)
        {
            var cs = curveArray.GetEnumerable();

            Curve? arcOrLine = cs.FirstOrDefault(t => t is Arc);

            if (arcOrLine is null)
            {
                arcOrLine = cs.FirstOrDefault(t => t is Line);
            }

            if (arcOrLine is null)
            {
                throw new NotImplementedException("参数‘curve’必须是 Line或Arc类型");
            }

            XYZ normal;
            XYZ origin;

            if (arcOrLine is Arc arc)
            {
                normal = arc.Normal;
                origin = arc.Tessellate().First();
            }
            else if (arcOrLine is Line line)
            {
                normal = line.Direction.GetVerticalDirection();
                origin = line.Origin;
            }
            else
            {
                throw new NotImplementedException("'plane'参数为null，函数在自行创建时需要'curve'参数必须是 Line或Arc类型");
            }

#if rvt16
            plane = new Plane(normal, origin);
#else
            plane = Plane.CreateByNormalAndOrigin(normal, origin);
#endif
        }
        if (isFamilyCreate)
        {
            return doc.FamilyCreate.NewModelCurveArray(curveArray, SketchPlane.Create(doc, plane));
        }
        else
        {
            return doc.Create.NewModelCurveArray(curveArray, SketchPlane.Create(doc, plane));
        }
    }

    /// <summary>
    /// 转换成详图线
    /// </summary>
    /// <param name="curveArray"></param>
    /// <param name="doc"></param>
    /// <param name="view"></param>
    /// <param name="isFamilyCreate"></param>
    /// <returns></returns>
    public static DetailCurveArray ConvertToDetailCurveArray(this CurveArray curveArray, Document doc, View? view = null, bool isFamilyCreate = false)
    {
        view = view ?? doc.ActiveView;

        if (isFamilyCreate)
        {
            return doc.FamilyCreate.NewDetailCurveArray(view, curveArray);
        }
        else
        {
            return doc.Create.NewDetailCurveArray(view, curveArray);
        }
    }
}
